<!--
 * @Description: 文件Url插入弹窗
 * @Author: HuiSir<https://gitee.com/huisir001>
 * @Date: 2025-08-08 09:35:37
 * @LastEditTime: 2025-08-10 22:53:01
-->
<template>
  <el-dialog
    v-model="showDialog"
    title="从URL插入文件"
    append-to-body
    destroy-on-close
    @opened="bindDialogOpen"
    @closed="fileUrl = ''"
  >
    <el-form-item label="文件URL" label-width="70">
      <el-input
        ref="inputRef"
        v-model="fileUrl"
        placeholder="输入文件URL下载链接"
      ></el-input>
      <p>
        链接以<el-text type="warning">http</el-text>或<el-text type="warning"
          >https</el-text
        >开头，以<el-text type="warning">文件扩展名</el-text>结尾，例如
        <el-text type="primary">https://abc.com/a.txt</el-text>
      </p>
    </el-form-item>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: "UrlInsertDialog",
};
</script>

<script lang="ts" setup>
import { ref, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { REG_EXP_PATTERN, MIME_TYPE } from "../../helpers/constant";
import { getUrlFileExt } from "../../helpers";

const showDialog = defineModel({
  type: Boolean,
  default: false,
});
const fileUrl = ref("");

const emit = defineEmits(["submit"]);

const inputRef = ref();

const bindDialogOpen = () => {
  // 获取焦点
  nextTick(inputRef.value.focus);
};

const submit = () => {
  const url = fileUrl.value.trim();
  if (!url) {
    ElMessage.error("请输入文件URL！");
    return;
  }
  if (!REG_EXP_PATTERN.url.test(url)) {
    ElMessage.error("请输入正确的URL！");
    return;
  }

  const extName = getUrlFileExt(url);

  if (!MIME_TYPE[`.${extName}`]) {
    ElMessage.error(`不允许文件URL扩展类型为${extName}！`);
    return;
  }

  emit("submit", url);
};
</script>
